import styles from "@styles/channel.module.less";
import classNames from "classnames";
import React, { useEffect, useRef } from "react";
import useChannelScroll from "@pages/home/common/useChannelScroll";
import { useRequestUserChannelsQuery } from "@service/channelEndpoints";
import { useNavigate, useParams } from "react-router-dom";

export default function UserChannel() {
  const { data } = useRequestUserChannelsQuery(undefined);
  const { scrollContainerRef, scrollHandler } = useChannelScroll();
  // 用于根据频道 id 存储对应的 DOM 对象
  const elements = useRef<Record<string, HTMLDivElement>>({});
  const { cid } = useParams();
  const navigate = useNavigate();

  // 监听 cid 变化
  useEffect(() => {
    if (scrollContainerRef.current === null) return;
    scrollHandler(elements.current[cid!]);
  }, [cid, scrollContainerRef, scrollHandler]);

  if (typeof data === "undefined") return null;
  return (
    <div className={styles.list} ref={scrollContainerRef}>
      {data.data.channels.map((channel) => (
        <div
          onClick={() => {
            navigate(`/${channel.id}`);
          }}
          key={channel.id}
          ref={(element) => (elements.current[channel.id] = element!)}
          className={classNames(styles.item, {
            [styles.active]: Number(channel.id) === Number(cid),
          })}
        >
          {channel.name}
        </div>
      ))}
    </div>
  );
}
